package com.macaline.service.impl.user;

import com.macaline.bean.Result;
import com.macaline.mapper.UserMapper;
import com.macaline.service.base.BaseService;
import com.macaline.service.user.LoginService;
import com.macaline.util.LoginUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    UserMapper userMapper;

    @Override
    public Result loginByUserNameAndPassWord(HttpServletRequest request, String userName, String passWord) {
        // 使用账号密码创建凭证
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userName, passWord);
        // 验证登录信息
        try {
            Subject subject = SecurityUtils.getSubject();
            usernamePasswordToken.setRememberMe(true);
            subject.login(usernamePasswordToken);
            subject.getSession();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败");
        }
        return getLoginUserInfo();
    }

    @Override
    public void logout(HttpServletRequest request) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

    /**
     * 获取登录用户信息
     * @return
     */
    private Result getLoginUserInfo(){
        Result baseVo = new Result();
        baseVo.setData(LoginUtil.getUser());
        return baseVo;
    }
}
